﻿using Refit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;
using System.Text;
using System.Threading.Tasks;

namespace Service
{
    [MyProxy]
    public class serviceTest : MarshalByRefObject
    {
        IService serviceUrl = RestService.For<IService>("http://localhost:5001/Api");
                
        public async Task<string[]> GetValues()
        {
            var value = await serviceUrl.GetValue();
            return value;
        }
    }

    [AttributeUsage(AttributeTargets.Class)]
    public class MyProxyAttribute : ProxyAttribute
    {
        public MyProxyAttribute()
        {
        }
        // Create an instance of ServicedComponentProxy
        public override MarshalByRefObject CreateInstance(Type serverType)
        {
            MarshalByRefObject obj = base.CreateInstance(serverType);
            Proxy proxy = new Proxy(serverType, obj);
            return (MarshalByRefObject)proxy.GetTransparentProxy();
        }
    }

    public class Proxy : RealProxy
    {
        public serviceTest instance = null;
        MarshalByRefObject _target = null;
        public Proxy(Type t, MarshalByRefObject plane) : base(t)
        {
            this._target = plane;
        }
        public override IMessage Invoke(IMessage msg)
        {
            Console.WriteLine("代理方法");
            var methodCall = (IMethodCallMessage)msg;
            var result = methodCall.MethodBase.Invoke(_target, methodCall.Args);
            try
            {
                var task = result as Task;
            }
            catch (Exception e)
            { 
            
            }
            return new ReturnMessage(result, null, 0, methodCall.LogicalCallContext, methodCall);
        }

        private async void awaitTask(Task task)
        {
            await task;
        }

        private void HandelException(Task t)
        {
            var a = t.ConfigureAwait(true);
        }
    }
}
